package es.spider.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;
import org.springframework.stereotype.Service;

import es.spider.dao.Pelicula;
import es.spider.service.ISearchFilmsService;

@Service("filmAffinityService")
public class FilmAffinityService implements ISearchFilmsService {
	
	/**
	 * Parsea el html perteneciente a la url pasada como
	 * parametro, recuperando una lista de titulos
	 * 
	 * @param url	Url que contiene el listado de titulos
	 * @return
	 */
	public List<Pelicula> getPelis (String url) {
		
		List<Pelicula> lista = new ArrayList<Pelicula>();
		
		try {	
			Parser	parser = new Parser(url);
			//parser.setEncoding("UTF-8");
			NodeList aList = parser.extractAllNodesThatMatch (new TagNameFilter ("A"));
			SimpleNodeIterator aIt = aList.elements();
			Pelicula peli = null;
			while (aIt.hasMoreNodes()){
				Node node = aIt.nextNode();
				if (node.getText().contains("http://www.filmaffinity.com/es/film")){
					
					if (node.getFirstChild().getClass().getSimpleName().equals("TextNode")){
						String titulo = node.getFirstChild().getText().replaceAll("\r","").replaceAll("\n","").replaceAll("  ","");
						System.out.println("Titulo ["+titulo+"]");
						peli.setTitulo(titulo);
						
						TableTag table = (TableTag)node.getParent().getParent().getParent();
						Lexer lex = new Lexer(table.getChildrenHTML());
						Parser actorParser = new Parser (lex);
						NodeList actorList = actorParser.extractAllNodesThatMatch(new TagNameFilter("DIV"));
						if (actorList.size()>0){
							Node n = actorList.elementAt(0);
							String actores = formaliza(n.getFirstChild().getText()).replace(", ",",");
							System.out.println("Actores ["+actores+"]");
							String[] s = actores.split(",");
							for (String nombre:s){
								peli.getActores().add(nombre);	
							}
							lista.add(peli);
						}
						
					}else if (node.getFirstChild().getClass().getSimpleName().equals("ImageTag")){
						peli = new Pelicula();
						peli.setActores(new ArrayList<String>());
						Tag portada = (Tag)node.getFirstChild();
						System.out.println("----------------------------------------------");
						System.out.println("Portada ["+portada.getAttribute("src")+"]");
						peli.setUrlPortada(portada.getAttribute("src"));
					}
				}	
			}
		} catch (ParserException e) {
			e.printStackTrace();
		}
		
		return lista; 
	}
	
	
	/**
	 * Parsea el html perteneciente a la url pasada como
	 * parametro, recuperando los detalles de la pelicula
	 * 
	 * @param abono
	 * @return
	 */
	public Pelicula getDetallePeli (String url) {
		
		Pelicula peli = new Pelicula();
		
		try {	
			Parser	parser = new Parser(url);
			parser.setEncoding("UTF-8");
			NodeList aList = parser.extractAllNodesThatMatch (new TagNameFilter ("A"));
			SimpleNodeIterator aIt = aList.elements();
			while (aIt.hasMoreNodes()){
				Node node = aIt.nextNode();
				if (node.getText().contains("http://www.filmaffinity.com/es/evideos.php?movie_id=")){
					System.out.println("Tipo ["+node.getFirstChild().getClass().getSimpleName()+"] Texto["+node.getFirstChild().getText()+"]");
					TableTag table = (TableTag)node.getParent().getParent().getParent().getParent().getParent().getParent();
					Lexer lex = new Lexer(table.getChildrenHTML());
					Parser tdParser = new Parser (lex);
					NodeList actorList = tdParser.extractAllNodesThatMatch(new TagNameFilter("TD"));
					SimpleNodeIterator it = actorList.elements();
					while (it.hasMoreNodes()){
						Node n = it.nextNode();	
						if (n.getFirstChild()!=null){
							if (n.getFirstChild().getClass().getSimpleName().equals("TagNode")){
								if (n.getFirstChild().getNextSibling().getText().contains("ORIGINAL")){
									Node titulo = it.nextNode();
									peli.setTituloOriginal(titulo.getFirstChild().getNextSibling().getText());
								}else if (n.getFirstChild().getNextSibling().getText().contains("AÑO")){
									Node aux = it.nextNode();
									Node anio = it.nextNode();
									peli.setAnio(anio.getFirstChild().getText());
									System.out.println("AÑO ["+anio.getFirstChild().getText()+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("DURACIÓN")){
									Node aux = it.nextNode();
									Node dur = it.nextNode();
									peli.setDuracion(dur.getFirstChild().getText());
									System.out.println("DURACION ["+dur.getFirstChild().getText()+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("DIRECTOR")){
									Node ndirector = it.nextNode();
									String director = formaliza(ndirector.getFirstChild().getFirstChild().getText());
									peli.setDirector(director);
									System.out.println("DIRECTOR ["+director+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("GUIÓN")){
									Node nguion = it.nextNode();
									peli.setGuion(nguion.getFirstChild().getText());
									System.out.println("GUION ["+nguion.getFirstChild().getText()+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("MÚSICA")){
									Node nmusica = it.nextNode();
									peli.setMusica(nmusica.getFirstChild().getText());
									System.out.println("MÚSICA ["+nmusica.getFirstChild().getText()+"]");
								}else if (n.getFirstChild().getNextSibling().getText().contains("FOTOGRAFÍA")){
									Node nfoto = it.nextNode();
									peli.setFotografia(nfoto.getFirstChild().getText());
									System.out.println("FOTOGRAFÍA ["+nfoto.getFirstChild().getText()+"]");
								}
							}
						}
					}
				}	
			}
			// Busqueda de la valoracion
			peli.setValoracionFilmAffinity(getValoracion(url));
			
		} catch (ParserException e) {
			e.printStackTrace();
		}
		return peli; 
	}
	
	/**
	 * Recupera la valoracion incluida en la url pasada como parametro
	 * 
	 * @param url
	 * @return
	 */
	public String getValoracion(String url){
		
		String valoracion="";
		
		try {
			
			Parser parser = new Parser(url);
			parser.setEncoding("UTF-8");
			
			NodeList objetList = parser.extractAllNodesThatMatch (new TagNameFilter ("OBJECT"));
			SimpleNodeIterator objetIt = objetList.elements();
			Node node = objetIt.nextNode();
			
			NodeList tdList = node.getParent().getParent().getPreviousSibling().getPreviousSibling().getChildren();
			Node tdAux = node.getParent().getParent().getPreviousSibling().getPreviousSibling().getPreviousSibling().getPreviousSibling();
			String val = tdAux.getChildren().elementAt(1).getChildren().elementAt(0).getText().trim();
			
			NodeList tdList2 = node.getParent().getParent().getNextSibling().getNextSibling().getChildren();
			String total = tdList2.elementAt(1).getChildren().elementAt(0).getText();
			
			valoracion = val+" "+total;
			System.out.println("VALORACION ["+val+"] TOTAL["+total+"]");
		
		} catch (ParserException e) {
			e.printStackTrace();
		}
			
		return valoracion;
		
	}
	
	
	
	private String formaliza (String texto){
		return texto.replaceAll("\n","").replaceAll("\r","").replaceAll("  ","").replace(", ",",");
	}

}

